
<div style="margin: 10px 10px 10px 10px">
    <form class="layui-form layui-form-pane" action="">
        <div class="layui-form-item">
              <div class="layui-inline">
                <div class="layui-input-inline">
                  <input id="s_time" type="text" name="s_time" lay-verify="required"  placeholder="开始时间" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <div class="layui-input-inline">
                  <input id="e_time" type="text" name="e_time" lay-verify="required"  placeholder="结束时间" autocomplete="off" class="layui-input">
                </div>
              </div>
            <div class="layui-inline" >
              <div class="layui-input-inline" style="width: 300px">
                <select name="chose_device" id="chose_device" xm-select="select" xm-select-type="1"  xm-select-search="" xm-select-height="36px" >
                </select>
              </div>
            </div>
            <div class="layui-inline">
                <a class="layui-btn" lay-submit="" lay-filter="data-search-btn">查询</a>
            </div>
        </div>
    </form>
</div>
<!-- 报警数据表格开始 -->
<table class="layui-table" id="alarm_report_table" lay-filter="alarm_report_table"></table>
<script type="text/html" id="alarm_report_bar">
    <a class="layui-btn layui-btn-xs " lay-event="show_alarm_detail">图表展示</a>
</script>
<!-- 报警数据表格结束 -->
<!-- e_chart部分开始 -->
<div class="layui-coutainer" style="display:none" id="echarts_div">
 <div class="layui-row" >
  <div class="layui-col-lg6">
    <div  id="radar_chart" style="width:100%;height:300px;margin:0 auto;"></div>
  </div>
  <div class=" layui-col-lg3" id="half_panle">
    <br><br>
    <div  class="layui-form-item" id="dymanic_add_data"></div>
  </div>
  <div class=" layui-col-lg3" id="half_panle">
    <br><br>
    <div  class="layui-form-item" id="dymanic_add_data1"></div>
  </div>
  </div>
  <br><br>
  <div class="layui-row" id="echarts_detail_div">
      <div  id="report_data_detail" style="width:100%;height:250px"></div>
  </div>

</div>
<!-- e_chart部分结束 -->
<!-- js代码开始 -->
<!-- 引用echart插件 -->
<script src="/static/echartsjs/echarts.min.js"></script>
<script type="text/javascript">

form.render()
// 图标的宽度和高度的适应屏幕处理
var radar_chart_width=get_width/3
var radar_chart_height=get_height/2.2
$('#radar_chart').attr('style','height:'+radar_chart_height+'px;width:'+radar_chart_width+'px;')
var report_data_detail_height=get_height/3.2
var report_data_detail_width=get_width/1.1
$('#report_data_detail').attr('style','height:'+report_data_detail_height+'px;width:'+report_data_detail_width+'px;')


// 设备数据表格渲染函数
var alarm_report_table=function(table_data){
  table.render({
    elem: '#alarm_report_table',
    data: table_data,
    toolbar: true,
    title:'报警数据',
    id:'alarm_report_table',
    cols: [
    [   {
        field: 'name', 
        title: '名称',
        sort:true,
        templet:function(row){
          var device_name=get_detail_from_id(device,row.device_id);
          return device_name['name']
        }}
      , {
        field: 'efence',
        title: '围栏报警',
        templet:function(row){
          return '<p>'+row.efence.length.toString()+'次</p>'
        }
    }, 
    {
        field: 'polyline',
        title: '路线偏移',
        templet:function(row){
          return '<p>'+row.polyline.length.toString()+'次</p>'
        }
    }, {
        field: 'speed_alarm',
        title: '超速报警',
        templet:function(row){
          return '<p>'+row.speed_alarm.length.toString()+'次</p>'
        }
    },   {
        field: 'stop_alarm',
        title: '停留超时',
        templet:function(row){
          return '<p>'+row.stop_alarm.length.toString()+'次</p>'
        }  
    },  
    {
        field: 'sos_alarm',
        title: 'SOS报警',
        templet:function(row){
          return '<p>'+row.sos_alarm.length.toString()+'次</p>'
        }
    },
        {title: '操作',templet: '#alarm_report_bar', fixed: "right", align: "center"}
    ]],
    limits: [10, 15, 20, 25, 50, 100],
    limit: 10,
    page: true
  });
}

// 健康数据查询的ajax
var get_report_data_detail='0';
var alarm_reports_ajax=function(query_param,query_detail){

    query_param=JSON.stringify(query_param)
  console.log(query_param)
   $.ajax({
          type: 'POST',
          url:"/alarm_reports/?what="+'alarm_reports',
          dataType: 'json',
          async:true,
          data:{query_param},
          success: function( data) {
          console.log(data)
          
          if(query_detail!=='chart'){
            alarm_report_table(data)
          }else{
            // 加载详细数据
            get_report_data_detail=data
            layer.msg('数据加载完成')
            option1['series'][0]['data']=get_report_data_detail[0]['step_count_detail_yAxis']
            option1['xAxis']['data']=get_report_data_detail[0]['step_count_detail_xAxis']
            option1['title']['text']='运动步数'
            option1['legend']['selected']['运动步数']=true
            report_data_detail_chart.setOption(option1) 
          }
        },
        error:function (edata) {
              console.log(edata)
          }
      }); 

}


// 监听设备搜索操作
form.on('submit(data-search-btn)', function (data) {
  var search_key = data.field;
  var s_time=search_key['s_time'];
  var e_time=search_key['e_time'];
  console.log(formSelects.value('select', 'val'))
  query_param={'hard_id':formSelects.value('select', 'val'),'s_time':s_time,'e_time':e_time,'query_detail':'no'}
  alarm_reports_ajax(query_param,'table')
  return false;
});
// 监听图表展示按钮
table.on('tool(alarm_report_table)',function(obj){
  console.log(obj)
  layer.open({
        type: 1
        ,title:'健康数据展示:'
        ,area:['100%','92%'] 
        ,offset:'60px'
        ,id: 'health_reports_chart' //防止重复弹出
        ,content:$('#echarts_div')
        ,zIndex:999
        ,success:function(layero){
          show_chart(obj.data)
        }
        ,shade: 0 //不显示遮罩

        
      });
})
// 图标展示功能函数
var option1
var report_data_detail_chart
var show_chart=function(device_data){
  // device_data=JSON.parse(device_data)
  // console.log(device_data)
  // query_data(device_id)
  var step_max=10000/86400
  var radar_value=[]
  radar_value.push(device_data['step_count']/device_data['all_query_time'])
  radar_value.push(device_data['all_stop_time']/(device_data['all_query_time']/3600))
  radar_value.push(device_data['sleep_time']/(device_data['all_query_time']/3600))
  radar_value.push(device_data['heart_rate'])
  radar_value.push(device_data['blood_pres']['l_pres'])
  radar_value.push(device_data['blood_pres']['h_pres'])
  // console.log(radar_value)
  // 基于准备好的dom，初始化echarts实例
  var radar_chart = echarts.init(document.getElementById('radar_chart'));

  // 指定图表的配置项和数据
  var option = {
      // title: {
      //     text: '健康统计'
      // },
      legend: {
          data: []
      },
      radar: [
          {
              indicator: [
                  { text: '运动步数', max: 20000/86400 },
                  { text: '停留时长', max: 1 },
                  { text: '睡眠时长', max: 16/24 },
                  { text: '平均心率', max: 125 },
                  { text: '血压底压', max: 112 },
                  { text: '血压高压', max: 175 }
              ],
              center: ['60%', '50%'],
              radius: 120
          }
      ],
      series: [
          {
              name: '健康数据',
              type: 'radar',
              data: [
                  {
                      value: radar_value,
                      name: '李四',
                      areaStyle: {
                          normal: {
                              opacity: 0.9,
                              color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
                                  {
                                      color: '#B8D3E4',
                                      offset: 0
                                  },
                                  {
                                      color: '#72ACD1',
                                      offset: 1
                                  }
                              ])
                          }
                      }
                  }
              ]
          }
      ]
  }
  radar_chart.setOption(option);
  var show_field=['sex','name','picture','department','worknumber','job','phone','character']
  var show_field_dict={'sex':'性别','name':'姓名','picture':'照片','department':'部门','worknumber':'编号','job':'职位','character':'编制','phone':'电话'}
  var input

  $('#dymanic_add_data1').empty()
  $('#dymanic_add_data').empty()
  for(var i=0;i<device.length;i++){
    if(device[i]['device_id']==device_data['device_id']){
      // console.log(device[i])
      for (var k in device[i]) {
        if(show_field.indexOf(k)!==-1){
          if(k=='id'){
          }else if(k=='picture'){

            input_1='<div class="layui-inline">'+
            '<input type="text" value="" id="'+k+'" class="layui-input " style="background:url('+device[i][k]+') no-repeat ;background-size:contain; width:200px; height:235px;"></div>'
            $('#dymanic_add_data1').append(input_1)

          }else if(k=='show_icon'){
            
          }else{
            input='<div class="layui-inline" > <label class="layui-form-label">'+show_field_dict[k]+'</label>'+
            '<input readonly type="text" id="'+k+'" value="'+device[i][k]+'" class="layui-input " style="width: 160px;" ></div>'
          }  

            if($('#'+k).val()==null){
              $('#dymanic_add_data').append(input)
            }   
        }
      }
    }
  }
  // var person_data=query_data_by_device_id(device_data['device_id'])
  
  option1 = {
      title: {
          text: '健康数据详情'
          // subtext: '纯属虚构'
      },
      tooltip: {
          trigger: 'axis'
      },
      legend: {
          data:['运动步数','心率','停留时长','睡眠时长','血压高压','血压低压'],
          selected:{'运动步数':false,'心率':false,'停留时长':false,'睡眠时长':false,'血压高压':false,'血压低压':false}
      },
      toolbox: {
          show: true,
          feature: {
              dataZoom: {
                  yAxisIndex: 'none'
              },
              dataView: {readOnly: false},
              magicType: {type: ['line', 'bar']},
              restore: {},
              saveAsImage: {}
          }
      },
      xAxis:  {
          type: 'category',
          boundaryGap: false,
          data: []
      },
      yAxis: {
          type: 'value',
          // axisLabel: {
          //     templet: '{value} °C'
          // }
      },
      series: [
          
          {
              name:'运动步数',
              type:'line',
              data:[],
              markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          },
          {
              name:'心率',
              type:'line',
              data:[],
              markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          },{
              name:'停留时长',
              type:'line',
              data:[],
              markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          },{
              name:'睡眠时长',
              type:'line',
              data:[],
              markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          },{
              name:'血压高压',
              type:'line',
              data:[],
              markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          },{
              name:'血压低压',
              type:'line',
              data:[],
              markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          }
      ]

  };
  //   report_data_detail_chart.on('click', function (e) {
  //     console.log(e);
  // });


  // 判断是否需要重复加载
  // console.log(typeof(get_report_data_detail))
  if(typeof(get_report_data_detail)=='object'){
    console.log(get_report_data_detail[0]['device_id'],device_data['device_id'])
    if(get_report_data_detail[0]['device_id']!==device_data['device_id']){
      get_report_data_detail='0'
    }
  }
  // 加载详细数据
  // console.log(get_report_data_detail)
  if(get_report_data_detail=='0'){
    var s_time=$('#s_time').val();
    var e_time=$('#e_time').val();
    query_param={'hard_id':[device_data['device_id']],'s_time':s_time,'e_time':e_time,'query_detail':'chart'}
    alarm_reports_ajax(query_param,'chart')
    // 无法停止整个语句执行，感觉无用
    // var wait_load_data=function(){
    //   if(typeof(get_report_data_detail)!=='object'){
    //     setTimeout(function(){
    //       console.log('waiting_data.........')
    //       wait_load_data()
    //     },2000)
    //   }
    // }
    // wait_load_data()
    
  }

  report_data_detail_chart = echarts.init(document.getElementById('report_data_detail'));
  report_data_detail_chart.on('legendselectchanged', function (params) {
    console.log(params['name']);
    report_data_detail_dict={'运动步数':['step_count_detail_xAxis','step_count_detail_yAxis'],
                             '心率':['heart_rate_detail_xAxis','heart_rate_detail_yAxis'],
                             '停留时长':['stop_detail_xAxis','stop_detail_yAxis'],
                             '睡眠时长':['sleep_time_detail_xAxis','sleep_time_detail_yAxis'],
                             '血压高压':['h_pres_detail_xAxis','h_pres_detail_yAxis'],
                             '血压低压':['l_pres_detail_xAxis','l_pres_detail_yAxis']}
      
    var key_xaxis=report_data_detail_dict[params['name']][0]
    var key_yaxis=report_data_detail_dict[params['name']][1]

    option1['xAxis']['data']=get_report_data_detail[0][key_xaxis]
    for(var i=0;i<option1['series'].length;i++){
      if(option1['series'][i]['name']==params['name']){
        option1['series'][i]['data']=get_report_data_detail[0][key_yaxis]
        // option1['legend']['selected'][params['name']]=true
        for(var k in option1['legend']['selected']){
          if(k==params['name']){
            option1['legend']['selected'][params['name']]=true
          }else{
            option1['legend']['selected'][k]=false
          }
        }
        option1['title']['text']=params['name']
      }
    }
    console.log(get_report_data_detail)
    report_data_detail_chart.setOption(option1) 
  });

  report_data_detail_chart.setOption(option1)

}

//添加选择设备列表
$(function(){ 
      $('#chose_device').empty()
      for (var i = device.length - 1; i >= 0; i--) {
        var option='<option value="'+device[i]['device_id']+'">'+device[i]['name']+'</option>'
      $('#chose_device').append(option)
      }
      formSelects.render()
  }); 

// 时间选择框渲染
laydate.render({
  elem: '#s_time'
  ,type: 'datetime'
  ,value:new Date(new Date(new Date().toLocaleDateString()).getTime())
  ,btns: ['clear','now', 'confirm']
});

laydate.render({
  elem: '#e_time'
  ,type: 'datetime'
  ,value:new Date()
  ,btns: ['clear','now', 'confirm']
});

</script>